package com.kingmed.kmss.bpmn.flow.helper;

import java.util.Collection;
import java.util.List;

import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.SubProcess;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;


@Service
public class BpmnHelper {

	@Autowired
	ProcessEngine processEngine;
	
    @Autowired
    TaskService taskService;

    @Autowired
    HistoryHelper historyHelper;

    @Autowired
    RepositoryService repositoryService;
    
    @Autowired
	RuntimeService runtimeService;
    
    public BpmnHelper(TaskService taskService) {
        super();
        this.taskService = taskService;
    }

   // public void setProcessInstanceVar(String String name, String value)
    public void listProcessNodeByInstanceId(String processInstanceId) {
    	String definitionId = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult().getProcessDefinitionId();
    	//获取所有节点信息
    	List<org.flowable.bpmn.model.Process> processes = repositoryService.getBpmnModel(definitionId).getProcesses();
    	System.out.println("processes size:" + processes.size());
    	//List<List<NextNode>> nextNodes = new ArrayList<>();
    	for (org.flowable.bpmn.model.Process process : processes) {
    	    Collection<FlowElement> flowElements = process.getFlowElements();
    	    if (CollectionUtils.isNotEmpty(flowElements)) {
    	        for (FlowElement flowElement : flowElements) {
    	        	 System.out.println("Elements：" + flowElement.getName());
    	        	 
    	            if (flowElement instanceof UserTask) {
    	               // System.out.println("UserTask：" + flowElement.getName());
    	               //业务操作
    	            }
    	            if (flowElement instanceof SubProcess) {
    	               //，，，
    	            }
    	 
    	        }
    	    }
    	}
    }

    public void isProcessFinished(String procInstId) {
    	HistoricProcessInstance hpi = processEngine.getHistoryService()   //与执行法的历史信息相关的Service
                .createHistoricProcessInstanceQuery()   //创建流程实例的历史信息查询对象
                .processInstanceId(procInstId)   //查询条件 -- 通过流程实例查询历史信息
                .singleResult();    //返回查询结果
                /**
                *	输出查询的记过
                **/
        System.out.println("历史信息ID："+hpi.getId());
        System.out.println("流程定义ID："+hpi.getProcessDefinitionId());
        System.out.println("流程开始时间："+hpi.getStartTime());
        System.out.println("流程结束时间："+hpi.getEndTime());

    }
   
}
